package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.api.IWemediaClient;
import com.heima.model.admin.dtos.AuthDto;
import com.heima.model.admin.pojos.ApUserRealname;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.AuthMapper;
import com.heima.user.service.IAuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthServiceImpl extends ServiceImpl<AuthMapper, ApUserRealname> implements IAuthService {

    @Autowired
    private AuthMapper authMapper;

    @Autowired
    private IWemediaClient wemediaClient;

    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * 用户审核列表查询
     * @param authDto
     * @return
     */
    @Override
    public ResponseResult list(AuthDto authDto) {
        authDto.checkParam();

        IPage<ApUserRealname> page = new Page<>(authDto.getPage(), authDto.getSize());

        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery();
        wrapper.eq(authDto.getStatus() != null, ApUserRealname::getStatus, authDto.getStatus());
        authMapper.selectPage(page, wrapper);

        PageResponseResult result = new PageResponseResult(authDto.getPage(), authDto.getSize(), (int) page.getTotal());

        result.setData(page.getRecords());

        return result;
    }

    /**
     * 审核失败
     * @param authDto
     * @return
     */
    @Override
    public ResponseResult fail(AuthDto authDto) {

        ApUserRealname apUserRealname = new ApUserRealname();
        BeanUtils.copyProperties(authDto,apUserRealname);

        apUserRealname.setStatus(2);
        return ResponseResult.okResult(authMapper.updateById(apUserRealname));
    }

    /**
     * 审核通过
     * @param authDto
     * @return
     */
    @Override
    public ResponseResult pass(AuthDto authDto) {
        ApUserRealname apUserRealname = new ApUserRealname();
        BeanUtils.copyProperties(authDto,apUserRealname);
        apUserRealname.setUserId(authDto.getId());
        apUserRealname.setStatus(9);


        // 调用微社区接口创建用户
        ApUser user = apUserMapper.selectById(apUserRealname.getUserId());

        wemediaClient.createUser(user);
        return ResponseResult.okResult(authMapper.updateById(apUserRealname));
    }
}
